package com.dgut.service.serviceImpl;

import com.dgut.dao.RecordDao;
import com.dgut.pojo.Record;
import com.dgut.service.RecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
@CacheConfig(cacheNames = "recordCache")
public class RecordServiceImpl implements RecordService {
    @Autowired
    private RecordDao recordDao;
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public void savaRecord(Record r) {
        recordDao.save(r);
    }

    @Override
    public List<Record> findRecordById(Long id) {
        return recordDao.findAllById(id);
    }

    @Override
    @Cacheable(key = "#root.args[0]")
    public Record findTodayRecordById(Long id) {
        Record record = recordDao.findTodayRecordById(id);
        return record;
    }

    @Override
    public Record findLastDayRecordById(Long id) {
        return recordDao.findLastDayRecordById(id);
    }

    /**
     * 定时任务每天0点执行
     */
    @Override
    @Scheduled(cron = "0 0 0 * * ?")
    public void cleanRecordCache(){
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("*********************************");
        System.out.println("*********************************");
        System.out.println("*********************************");
        System.out.println("**********清理recordCache*********");
        System.out.println(simpleDateFormat.format(date));
        System.out.println("*********************************");
        System.out.println("*********************************");
        System.out.println("*********************************");
        Set<String> keysForDelete = new HashSet<>();
        Set<String> keys = redisTemplate.keys("*");
        for(String s:keys){
            if(s.startsWith("recordCache")){
                keysForDelete.add(s);
            }
        }
        redisTemplate.delete(keysForDelete);
    }

    @Override
    public Record findNewestRecordById(Long id) {
        return recordDao.findNewestRecordById(id);
    }
}
